package cn.bingoo.lang;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Scanner;

public class LenientNumberParser {
    public static void main(String[] args) throws ParseException {
        lenientParse("-77398757157105051D");

        strictParse("-77398757157105051D");
        strictParse("-7730");
    }

    public static void lenientParse(String input) throws ParseException {
        NumberFormat format = NumberFormat.getInstance();

        Number number = format.parse(input);

        System.out.println(number); // or use number.doubleValue()

        DecimalFormat format2 = (DecimalFormat) NumberFormat.getInstance();
        format2.setParseBigDecimal(true);
        BigDecimal number2 = (BigDecimal) format2.parse(input);
        System.out.println(number2);

    }

    // http://stackoverflow.com/questions/5888987/determine-if-a-string-is-a-number-and-convert-in-java
    public static void strictParse(String input) {
        // Scanner.useLocale can be used to change to the desired locale.
        Scanner scanner = new Scanner(input);
        if (scanner.hasNextInt()) {
            System.out.println(scanner.nextInt());
        }
        else if (scanner.hasNextDouble()) {
            System.out.println(scanner.nextDouble());
        }
        else {
            System.out.println("Not a number");
        }

    }

}
